//
//  VRTestingViewController.m
//  VRFirefighting
//
//  Created by Veer on 2018/8/23.
//  Copyright © 2018年 Veer. All rights reserved.
//1111111

#import "VRTestingViewController.h"

#import "UIImage+VR.h"

@interface VRTestingViewController () <UITextViewDelegate>

@property (nonatomic, strong) UITextView *editTextView;
@property (nonatomic, strong) UILabel *placeholderLbl;
@property (nonatomic, strong) UILabel *countdownLbl;
@property (nonatomic, strong) UIButton *saveBtn;

@property (nonatomic, strong) dispatch_source_t timer;
@property (nonatomic, assign) BOOL isCountDown;

@end

@implementation VRTestingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = ScrollViewBgColor;
    self.title = @"正在测试中";
    
    [self setupSubView];
    [self startCountDown];
}

- (void)setupSubView
{
    UIImageView *iconImgView = [[UIImageView alloc] init];
    iconImgView.image = [UIImage imageNamed:@"sby"];
    iconImgView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:iconImgView];
    [iconImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(NAVIGATION_BAR_HEIGHT + 20);
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(140);
        make.height.mas_equalTo(140);
    }];
    
    UIImageView *iconImgView1 = [[UIImageView alloc] init];
    iconImgView1.image = [UIImage imageNamed:@"sbblx"];
    iconImgView1.contentMode = UIViewContentModeScaleAspectFit;
    [iconImgView addSubview:iconImgView1];
    [iconImgView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(iconImgView).offset(-10);
        make.centerX.mas_equalTo(iconImgView);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(44);
    }];
    
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.text = @"测试中";
    titleLbl.textColor = RGB(78, 172, 57);
    titleLbl.font = VRFont(20);
    [iconImgView addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(iconImgView1.mas_bottom).offset(2);
        make.centerX.mas_equalTo(iconImgView);
    }];
    
    
    XButton *cancelBtn = [XButton buttonWithType:UIButtonTypeCustom];
    //    goCardPackageBtn.layer.cornerRadius = 2;
    //    goCardPackageBtn.layer.borderColor = RGB(248, 177, 90).CGColor;
    cancelBtn.layer.borderColor = RGB(225, 11, 24).CGColor;
    cancelBtn.layer.borderWidth = 1.0;
    [cancelBtn setTitle:@"取消测试" forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = VRFont(14);
    [cancelBtn setTitleColor:RGB(225, 11, 24) forState:UIControlStateNormal];
    [cancelBtn setTitleColor:RGB(211, 209, 209) forState:UIControlStateDisabled];
    [cancelBtn addTarget:self action:@selector(onCancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.centerY.mas_equalTo(iconImgView);
        make.width.mas_equalTo(76);
        make.height.mas_equalTo(32);
    }];
    
    // 中间倒计时条
    UIView *centerBgView = [[UIView alloc] init];
    centerBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:centerBgView];
    [centerBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(iconImgView.mas_bottom).offset(20);
        make.left.right.mas_equalTo(self.view);
        make.height.mas_equalTo(50);
    }];
    
    UIImageView *countDownImgView = [[UIImageView alloc] init];
    countDownImgView.image = [UIImage imageNamed:@"nz"];
    countDownImgView.contentMode = UIViewContentModeScaleAspectFit;
    [centerBgView addSubview:countDownImgView];
    [countDownImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.centerY.mas_equalTo(centerBgView);
        make.width.mas_equalTo(16);
        make.height.mas_equalTo(16);
    }];
    
    UILabel *countTitleLbl = [[UILabel alloc] init];
    countTitleLbl.text = @"剩余时间";
    countTitleLbl.textColor = MAINColor;
    countTitleLbl.font = VRFont(14);
    [centerBgView addSubview:countTitleLbl];
    [countTitleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(countDownImgView.mas_right).offset(6);
        make.centerY.mas_equalTo(centerBgView);
    }];
    
    UILabel *countLbl = [[UILabel alloc] init];
    countLbl.text = @"00:15:00";
    countLbl.textColor = RGB(78, 172, 57);
    countLbl.font = VRFont(22);
    [centerBgView addSubview:countLbl];
    self.countdownLbl = countLbl;
    [countLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(countTitleLbl.mas_right).offset(30);
        make.centerY.mas_equalTo(centerBgView);
    }];
    
    
    // 意见反馈
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT, kScreenWidth, 150);
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(centerBgView.mas_bottom).offset(10);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(180);
    }];
    
    UIImageView *feedbackImgView = [[UIImageView alloc] init];
    feedbackImgView.image = [UIImage imageNamed:@"my_report_describe"];
    feedbackImgView.contentMode = UIViewContentModeScaleAspectFit;
    [bgView addSubview:feedbackImgView];
    [feedbackImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(14);
        make.width.mas_equalTo(16);
        make.height.mas_equalTo(16);
    }];
    
    UILabel *feedbackTitleLbl = [[UILabel alloc] init];
    feedbackTitleLbl.numberOfLines = 0;
    feedbackTitleLbl.textColor = MAINColor;
    feedbackTitleLbl.font = VRFont(16);
    feedbackTitleLbl.text = @"意见反馈";
    [bgView addSubview:feedbackTitleLbl];
    [feedbackTitleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(feedbackImgView.mas_right).offset(4);
        make.centerY.mas_equalTo(feedbackImgView);
    }];
    
    // 创建textview
    UITextView *textView = [[UITextView alloc] init];
    textView.backgroundColor = [UIColor whiteColor];
    textView.font = VRFont(15);
    textView.delegate = self;
    textView.frame = CGRectMake(20, 40, kScreenWidth - 40, 140);
    self.editTextView = textView;
    [bgView addSubview:textView];
    
    NSString *placeholderStr = [NSString stringWithFormat:@"填写反馈意见"];
    UILabel *placeholderLbl = [[UILabel alloc] init];
    placeholderLbl.numberOfLines = 0;
    placeholderLbl.textColor = RGB(180, 180, 180);
    placeholderLbl.font = VRFont(15);
    placeholderLbl.text = placeholderStr;
    //    textView.text
    CGSize placeholderSize = [placeholderStr sizewithFont:placeholderLbl.font maxSize:CGSizeMake(textView.frame.size.width, MAXFLOAT)];
    [textView addSubview:placeholderLbl];
    self.placeholderLbl = placeholderLbl;
    placeholderLbl.frame = CGRectMake(4, 8, placeholderSize.width + 4, placeholderSize.height);
    
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.enabled = NO;
//    saveBtn.backgroundColor = RGB(78, 173, 57);
    saveBtn.layer.cornerRadius = 4;
    [saveBtn setTitle:@"提交" forState:UIControlStateNormal];
    saveBtn.titleLabel.font = VRFont(16);
    [saveBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    [saveBtn setTitleColor:RGB(120, 120, 120) forState:UIControlStateHighlighted];
    [saveBtn setBackgroundImage:[UIImage imageWithColor:RGB(78, 173, 57)] forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(onSaveBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveBtn];
    self.saveBtn = saveBtn;
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(bgView.mas_bottom).offset(40);
        make.width.mas_equalTo(290);
        make.height.mas_equalTo(40);
    }];
}


- (void)startCountDown
{
    __block NSInteger time = 60 * 15; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    weakify(self)
    dispatch_source_set_event_handler(_timer, ^{
        
        strongify(self)
        if(time <= 0){ //倒计时结束，关闭
            
            self.isCountDown = NO;
            dispatch_source_cancel(self.timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                self.saveBtn.enabled = YES;
            });
            
        }else{
            
            self.isCountDown = YES;
            NSInteger minutes = time / 60;
            NSInteger seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                self.countdownLbl.text = [NSString stringWithFormat:@"00:%02ld:%02ld", (long)minutes, (long)seconds];
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}


- (void)stopCountDown
{
    self.isCountDown = NO;
    dispatch_source_cancel(_timer);
}


#pragma mark - networking
- (void)cancelTest
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"fID"] = self.fID;
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [JKNetworking postWithSign:CancelTest parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [hud hideAnimated:YES];
                [SVProgressHUD showSuccessWithStatus:@"取消成功"];
            });
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
            });
        }
    } error:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
        });
    }];
}


#pragma mark - action
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)onSaveBtnClick:(UIButton *)sender
{
    [SVProgressHUD showSuccessWithStatus:@"测试完成"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.navigationController popViewControllerAnimated:YES];
    });
}


- (void)onCancelBtnClick:(UIButton *)sender
{
    [self cancelTest];
}

#pragma mark - Delegate
- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length > 0) {
        self.placeholderLbl.hidden = YES;
    }else{
        self.placeholderLbl.hidden = NO;
    }
}

- (void)dealloc
{
    [self stopCountDown];
}


@end
